/**
 * 
 */
package cn.jhz.filesharingsystem.web;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.jhz.filesharingsystem.model.User;
import cn.jhz.filesharingsystem.util.AuthUtil;

/**
 * @author asus
 *
 */
public class AuthIntercepertor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		String url= "";
		if(handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
//			Object Mapping = method.getAnnotation(RequestMapping.class);

			url = AuthUtil.getURL(method);
			//当前访问页面的权限标记
			
			//获取系统中所有权限控制的url标记
			@SuppressWarnings("unchecked")
			List<String> urls = (List<String>) request.getServletContext().getAttribute("allPermRes");
			
			//获取当前用户的所有权限url标记
			@SuppressWarnings("unchecked")
			Set<String> userAllpermRes = (Set<String>)session.getAttribute("userAllPermRes");
			
			User logUser = (User) session.getAttribute("loginUser");
			if(logUser == null) {
				response.sendRedirect(request.getContextPath()+"/login");
			}else {
				boolean isadmin = (boolean) session.getAttribute("isadmin");
				if(!isadmin && urls.contains(url)) {
					//进行权限控制:对比用户权限是否包含url
					if(!userAllpermRes.contains(url)) {
						throw new RuntimeException("无法访问该页面"+url);
					}
				}
			}
			
		}
		else {
			throw new RuntimeException("访问的页面不存在!");
		}
		
		
		return super.preHandle(request, response, handler);
	}

	
}
